import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 5000 // request timeout
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    //请求拦截器中，统一携带token
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    //状态码为2xx的，会走这里
    console.log(response)
    if (response.data.success) {
      return response.data
    } else {
      //统一提示错误消息
      Message.error(response.data.message)
      //当success为false时，要抛出错误
      return Promise.reject(response.data.error)
    }
  },
  error => {
    //状态码非2xx的，会走这里
    if (error.response.status === 401) {
      //提示用户
      Message.error('当前登录失效，请重新登录！')
      //清除token和用户信息
      store.commit('user/removeUserInfo')
      //跳转到登录页
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request
